package com.kaifamiao.thread.d0926;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketRunnable implements Runnable{

    private int ticket = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) { // 售票窗口一直开着
            lock.lock();
            sellTicket();
            lock.unlock();
        }

    }

    private void sellTicket(){
        //有票 可以卖
        if (ticket > 0) {
            //出票操作
            //使用sleep模拟一下出票时间
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //获取当前线程对象的名字
            String name = Thread.currentThread().getName();
            System.out.println(name + "正在卖第" + ticket-- + "张票");
        }
    }
}
